package cn.appsys.controller;

import cn.appsys.pojo.Appversion;
import cn.appsys.service.AppversionService;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;

@Log4j
@Controller
public class xiazai {
    @Autowired
    private AppversionService appversionService;

    @RequestMapping("xiazai")
    public String xiazai(@RequestParam Integer id, HttpServletRequest request, HttpServletResponse response) throws Exception{
        //一个头两个流
        InputStream is = null;
        OutputStream os = null;
        Appversion appversion=appversionService.getbanbenId(id);
        String name="";
        //获取该文件在服务器端的资源路劲，因为是从服务器下载文件
        //根据获取的路径，读入文件到内存中
        //从服务器端本地读入文件流
        is = new BufferedInputStream(new FileInputStream(appversion.getDownloadLink()));
        //解决文件名在下载时遇到中文出现乱码问题---反向编码一次
        //注意这个编码要在文件读取文件到输入流中之后，不然把文件名先改变编码后
        //在服务器端根据路径去读文件到输入流，会找不到这个文件，因为编码方式不同，文件名就改变了，后报错
        name = new String(appversion.getDownloadLink().getBytes("utf-8"),"iso-8859-1");
        response.addHeader("content-Disposition","attachment;fileName ="+name);
        byte[] b = new byte[1024];
        //写出到客户端的写入流
        os = response.getOutputStream();
        int len = -1;
        while((len=is.read())!=-1){
            os.write(b,0,len);
        }
        os.close();
        is.close();
        return "redirect:/dev/banbenmodify";
    }

}
